﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace NiuX.AspNetCore.Infrastructure.Filters;

public class RateLimitFilter : IAsyncActionFilter
{
    private readonly IMemoryCache _cache;
    public RateLimitFilter(IMemoryCache cache)
    {
        _cache = cache;
    }
    public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var removeIP = context.HttpContext.Connection.RemoteIpAddress?.ToString();
        var cacheKey = $"LastVisitTick_{removeIP}";
        var lastTick = _cache.Get<long?>(cacheKey);

        if (lastTick == null || Environment.TickCount64 - lastTick > 1000)
        {
            // TODO：这里是 10s
            _cache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));
            return next();
        }

        context.Result = new ContentResult { StatusCode = 429 };
        return Task.CompletedTask;
    }
}

/* sample

var builder = WebApplication.CreateBuilder(args);

// ...

builder.Services.Configure<MvcOptions>(options =>
{
    options.Filters.Add<RateLimitFilter>();
});
builder.Services.AddMemoryCache();

var app = builder.Build();

*/